<?php

class my extends bhCommon {



    public function index()
    {
        $images = array(
            'user_bg' => $this->images('user_bg', '067c7fa00031883c40dbc2968c353c49.jpeg'),
            'no_logo' => $this->image_url . 'da24cc5ba9602c72e9b38998b4023c5f.png',
            'completed' => $this->image_url . '441da76d0fec483616485508fae72f0d.png',
        );


        $unpaid = p_getcolumn('order', array('member_id' => $this->member['id'], 'status' => 1, 'is_pay' => 2), 'COUNT(*)') ? : 0;
        $paid = p_getcolumn('order', array('member_id' => $this->member['id'], 'status' => 2, 'deliver_status' => 1), 'COUNT(*)') ? : 0;
        $delivered = p_getcolumn('order', array('member_id' => $this->member['id'], 'status' => 2, 'deliver_status' => 2), 'COUNT(*)') ? : 0;

        $config = array(
            'open_withdrawal' => getConfig('open_withdrawal', 1),
            'video_ad_id' => getConfig('my_ad', 'adunit-96c594f54064b9c5'),
        );

        $data = array(
            'is_auth' => $this->is_auth,
            'member' => $this->member,
            'images' => $images,
            'unpaid' => $unpaid,
            'paid' => $paid,
            'delivered' => $delivered,
            'config' => $config
        );

        $this->json($data);
    }


    /**
     * 我的砍价列表
     */
    public function bargainLog()
    {
        $p = $this->get('p');

        $page_size = 10;
        $limit = ($p - 1) * $page_size;

        $order = p_getall('order', array('member_id' => $this->member['id']), array(), '', 'id desc', "{$limit},{$page_size}");

        if ($order) {
            foreach ($order as & $value) {
                $value['goods'] = p_get('goods', array('id' => $value['goods_id']));
                $value['goods']['cover_image'] = getImage($value['goods']['cover_image']);
            }
        }

        $data = array(
            'order' => $order
        );
        $this->json($data);
    }


    /**
     *
     */
    public function setAddress()
    {
        $data = array(
            'name' =>  $this->get('name'),
            'phone' =>  $this->get('phone'),
            'address' =>  $this->get('address'),
        );

        if ($address = p_get('address', array('member_id' => $this->member['id']))) {
            p_update('address', $data, array('id' => $address['id']));
        } else {
            $data['member_id'] = $this->member['id'];
            $data['created'] = time();
            p_insert('address', $data);
        }
        $this->json('设置成功');
    }


    /**
     *
     */
    public function getAddress()
    {
        $address = p_get('address', array('member_id' => $this->member['id']));
        $this->json(array('address' => $address));
    }


    /**
     * 注册wx_icon
     */
    public function register()
    {
        $iv = $this->get('iv');
        $encryptedData = $this->get('encryptedData');
        $wxbd = new WXBizDataCrypt($this->w['uniaccount']['key'], $this->session_key);

        $res = $wxbd->decryptData($encryptedData, $iv, $data);
        if ($res != ErrorCode::$OK) {
            //p_delete('token', array('member_id' => $this->member['id']));
            $this->json('更新失败', -1);
        }

        $data = json_decode($data, true);
        $member_id = $this->member['id'];

        if (empty($this->member['nickname']) && empty($this->member['head'])) {

            $auth_integral = getConfig('auth_integral');
            if (!p_get('integral_log', array('member_id' => $this->member['id'], 'type' => 8)) && $auth_integral > 0) {
                $this->bargain->change_integral($this->member['id'], $auth_integral, 8);
            }

            if ($this->member['parent_id'] > 0) {
                $row = $this->bargain->succ_share($this->member['parent_id'], $this->member['id']);
            }

            $update = array(
                'nickname' => $data['nickName'],
                'headimgurl' => $data['avatarUrl'],
                'city' => $data['city'],
                'province' => $data['province'],
                'country' => $data['country'],
                'sex' => $data['gender'],
            );
            p_update('member', $update, array('id' => $member_id));
        }

        $this->json();
    }


    /**
     * 道具
     */
    public function coupon()
    {
        $sql = 'SELECT A.id,A.coupon_id,A.expire,B.type,B.name,B.icon FROM ' . prefix('member_coupon') . ' AS A INNER JOIN ' . prefix('coupon') . ' AS B ON A.coupon_id=B.id WHERE A.member_id=' . $this->member['id'] . ' AND A.is_use=1 AND A.expire>' . time();

        $my_coupon = p_fetchall($sql);
        if ($my_coupon) {
            foreach ($my_coupon as & $value) {
                $value['icon'] = getImage($value['icon']);
                $value['expire'] = date('Y-m-d H:i:s', $value['expire']);
            }
        }

        $coupon = p_getall('coupon', array('is_delete' => 1));
        $coupon = arrayImage($coupon, 'icon');

        $config = array(
            'integral_name' => getConfig('integral_name', '积分')
        );

        $data = array(
            'my_coupon' => $my_coupon,
            'coupon' => $coupon,
            'config' => $config,
            'member' => $this->member
        );
        $this->json($data);
    }


    /**
     * 兑换道具
     */
    public function exchangeCoupon()
    {
        $id = intval($this->get('id'));

        $coupon = p_get('coupon', array('id' => $id, 'is_delete' => 1));
        if (empty($coupon)) {
            $this->json('道具不存在', 2);
        }
        pdo_begin();
        try{
            if (!$this->bargain->change_integral($this->member['id'], $coupon['integral'], 5)) {
                throw new Exception($this->bargain->error);
            }
            $insert = array(
                'member_id' => $this->member['id'],
                'coupon_id' => $id,
                'expire' => time() + ($coupon['worth'] * 86400),
                'created' => time()
            );
            if (!p_insert('member_coupon', $insert)) {
                throw new Exception('兑换失败');
            }
            pdo_commit();
            $this->json();
        } catch (Exception $e) {
            pdo_rollback();
            $this->json($e->getMessage(), 2);
        }

    }


    /**
     * 我的订单
     */
    public function order()
    {
        $type = $this->get('type', 0);

        $where = "member_id = {$this->member['id']}";
        if ($type == 0) {
            $where .= ' AND (A.status=2 OR A.is_pay=2)';
        } else if ($type == 1){
            $where .= ' AND (A.status=1 AND A.is_pay=2)';
        } else if ($type == 2) {
            $where .= ' AND (A.status=2 AND A.deliver_status=1)';
        } else {
            $where .= ' AND (A.status=2 AND A.deliver_status=2)';
        }

        $status = array(
            1 => array(
                'msg' => '待付款',
                'color' => '#FA2828'
            ),
            2 => array(
                'msg' => '已付款',
                'color' => '#FF8E00'
            ),
            3 => array(
                'msg' => '已发货',
                'color' => '#26BCC5'
            )
        );


        $sql = "SELECT A.*,B.name as goods_name,B.cover_image FROM " . prefix('order') . " AS A LEFT JOIN " . prefix('goods') . ' AS B ON A.goods_id=B.id WHERE ' . $where . " ORDER BY A.id DESC";

        $order = p_fetchall($sql);

        foreach ($order as & $value) {
            if ($value['status'] == 1) {
                $value['status_info'] = $status[1];
            } else if ($value['deliver_status'] == 1) {
                $value['status_info'] = $status[2];
            } else {
                $value['status_info'] = $status[3];
            }
            $value['cover_image'] = getImage($value['cover_image']);
        }
        $config = array(
            'integral_name' => getConfig('integral_name', '积分')
        );

        $data = array(
            'order' => $order,
            'config' => $config
        );
        $this->json($data);
    }



    /**
     * 绑定手机号
     */
    public function bindPhone()
    {
        $iv = $this->get('iv');
        $encryptedData = $this->get('encryptedData');

        if ($this->member['phone']) {
            //json('ok');
        }

        $wxbd = new WXBizDataCrypt($this->w['uniaccount']['key'], $this->session_key);

        $res = $wxbd->decryptData($encryptedData, $iv, $data);
        if ($res != ErrorCode::$OK) {
            p_delete('token', array('member_id' => $this->member['id']));
            $this->json('unlogin', -1);
        }

        $auth_phone = getConfig('auth_phone');

        if (!$this->member['phone'] && $auth_phone > 0 && !p_get('integral_log', array('member_id' => $this->member['id'], 'type' => 7))) {
            $this->bargain->change_integral($this->member['id'], $auth_phone, 7);
        }

        $data = json_decode($data, true);
        p_update('member', array('phone' => $data['purePhoneNumber']), array('id' => $this->member['id']));
        $this->json();
    }


    public function cash()
    {
        $cash_explain = getConfig('cash_explain');
        $cash_explain = $cash_explain ? json_decode($cash_explain, true) : '';


        $this->member['payment_code_url'] = getImage($this->member['payment_code']);

        $audit_model = audit_model() || getConfig('withdrawal_state') == 2;
        if ($audit_model) {
            $share_text = '真有趣';
        } else {
            $share_text = '邀请好友，一起领红包';
        }


        $data = array(
            'member' => $this->member,
            'cash_explain' => $cash_explain,
            'images' => array(
                'bg' => $this->images('cash_bg', 'userinfo_bg.png')
            ),
            'cash_type' => getConfig('cash_type', 2),
            'share_text' => $share_text,
            'tx' => getConfig('withdrawal_button_txt', '提现'),
            'audit_model' => $audit_model,
            'qq' => $this->member['qq']
        );
        if (isQq()) {
            if ($cash_money = getConfig('cash_money')) {
                $cash_money = json_decode($cash_money, true);
                $data['exchange_amount'] = $cash_money;
            }

        }

        $this->json($data);
    }



    /**
     * 提现
     */
    public function withdrawals()
    {
        $money = $this->get('money', 0);

        if ($money < 0.3) {
            $this->json('提现金额需要大于0.3元', 2);
        }

        $cash_num = p_getcolumn('withdrawals', array('member_id' => $this->member['id']), 'COUNT(*)') ? : 0;

        $cash_num = $cash_num + 1;
        $condition = p_get('withdrawals_condition', array('number' => $cash_num));
        if ($condition) {

            if ($condition['money'] != $money) {
                $this->json('本次只能提现' . $condition['money'] . '元', 2);
            }

            if ($condition['click_day'] > 0) {
                $days = $this->bargain->get_signin($this->member['id']);
                if ($condition['click_day'] > $days) {
                    $this->json('本次提现还需要坚持打卡' . ($condition['click_day'] - $days) . '天', 2);
                }
            }

            if ($condition['share_num'] > 0) {
                $share_num = p_getcolumn('member', array('parent_id' => $this->member['id']), 'COUNT(*)') ? : 0;
                //$this->json(($condition['share_num'] . '_' . $share_num . '_' . $this->member['id']), 2);
                if ($condition['share_num'] > $share_num) {
                    $this->json('本次提现还需要邀请' . ($condition['share_num'] - $share_num) . '人', 2);
                }
            }
        }


        $bag_daily_upper = getConfig('bag_daily_upper', 100);

        $time = strtotime(date('Y-m-d', time()));
        $sql = "SELECT SUM(money) FROM " . prefix('withdrawals') . " WHERE member_id={$this->member['id']} AND created>={$time}";
        if (pdo_fetchcolumn($sql) + $money > $bag_daily_upper) {
            $this->json('每天提现上限为' . $bag_daily_upper . '元', 2);
        }


        $withdrawals_day_number = getConfig('withdrawals_day_number', 2);
        $sql = "SELECT COUNT(*) FROM " . prefix('withdrawals') . " WHERE member_id={$this->member['id']} AND created>={$time}";
        if (pdo_fetchcolumn($sql) >= $withdrawals_day_number) {
            $this->json('每天提现次数为' . $withdrawals_day_number . '次，请明天再来', 2);
        }


        $cash_type = getConfig('cash_type', 2);
        if (isQq() && $cash_type == 1) {
            $qq = $this->get('qq');
            if (empty($qq)) {
                json('请填写当前qq号', 2);
            }
            p_update('member', array('qq' => $qq), array('id' => $this->member['id']));
        }

        $cash_reviewed = getConfig('cash_reviewed');



        $insert = array(
            'member_id' => $this->member['id'],
            'money' => $money,
            'success_time' => time(),
            'type' => $cash_type,
            'status' => 1,
            'created' => time()
        );

        if ($cash_type == 1 && $money < $cash_reviewed) {
            $insert['status'] = 2;
        }

        $m_update = array(
            'cash' => $this->member['cash'] + 1
        );
        if ($cash_type == 2) {
            $insert['payment_code'] = $this->get('payment_code');
            if (empty($insert['payment_code'])) {
                $this->json('请上传收款码', 2);
            }
            $m_update['payment_code'] = $insert['payment_code'];
        }

        pdo_begin();
        try{
            if (!$this->bargain->change_money($this->member['id'], $money, 3)) {
                throw new Exception($this->bargain->error);
            }
            if (!p_insert('withdrawals', $insert)) {
                throw new Exception('提现失败');
            }
            $pid = pdo_insertid();
            if ($insert['status'] == 2) {

                $this->setPayment();
                if (isQq()) {
                    if (!$this->bargain->qqCash($this->member['id'], $money, '', $pid)) {
                        throw new Exception($this->bargain->error);
                    }
                } else {
                    if (!$this->bargain->cash($money, $this->member['id'])) {
                        throw new Exception($this->bargain->error);
                    }
                }

            }
            p_update('member', $m_update, array('id' => $this->member['id']));
            pdo_commit();
            $this->json('');
        } catch (Exception $e) {
            pdo_rollback();
            $this->json($e->getMessage(), 0);
        }
    }


    public function moneyLog()
    {
        $log = p_getall('money_log', array('member_id' => $this->member['id']), array(), '', 'id desc');

        $types = array(
            '1' => '领取红包',
            '2' => '兑换红包',
            '3' => '提现',
            '4' => '抽奖红包',
            '5' => '兑换红包商品',
        );

        if ($log) {
            foreach ($log as & $value) {
                $value['type_msg'] = $types[$value['type']];
                $value['created'] = date('Y-m-d H:i:s', $value['created']);
            }
        }

        $data = array(
            'log' => $log,
            'food_name' => getConfig('food_name')
        );
        $this->json($data);
    }


    /**
     * 我的砍价
     */
    public function myBargain()
    {
        $sql = "SELECT A.id,A.price,A.bargain,A.time_end,A.status,B.cover_image,B.name FROM " . prefix('order') . " AS A INNER JOIN " . prefix('goods') . " AS B ON A.goods_id=B.id WHERE A.member_id={$this->member['id']}  ORDER BY A.id DESC";

        $bargain_goods = p_fetchall($sql);
        if ($bargain_goods) {
            foreach ($bargain_goods as & $value) {
                $value['cover_image'] = getImage($value['cover_image']);
                $value['surplus_time'] = $value['time_end'] - time();
                $value['surplus_money'] = round($value['price'] - $value['bargain']);
                $value['d'] = $value['h'] = $value['m'] = $value['s'] = '00';
            }
        }

        $data = array(
            'bargain_goods' => $bargain_goods
        );
        $this->json($data);
    }



    /**
     * 订阅消息
     */
    public function subscribe()
    {
        $new_activities = getConfig('new_activities');
        if (!empty($new_activities)) {
            $subscribe = p_get('subscribe', array('member_id' => $this->member['id']));
            if (empty($subscribe)) {
                $i = array(
                    'member_id' => $this->member['id'],
                    'new_activities' => 1,
                    'created' => time()
                );
                p_insert('subscribe', $i);
            } else {
                p_update('subscribe', array('new_activities' => $subscribe['new_activities'] + 1), array('id' => $subscribe['id']));
            }
        }
    }
}